<?php
namespace App\Repositories;

use App\Enums\MallEnum;
use App\Exceptions\BasicException;
use App\Response\Response;
use Illuminate\Support\Facades\Hash;
use function Matrix\add;    //引入hash

class MallCategoriesRepository
{
    /**
     * 获取商品分类列表
     * @return bool
     */
    public function getCategoryList()
    {
        $list = app('model_mall_categories')->select('id','title')->get()->toArray();
        return $list;
    }

    /**
     * 新增商品分类
     * @param $param
     * @return bool
     * @throws BasicException
     */
    public function  addType($param){
        $addType = app('model_mall_categories')->create($param);
        if ($addType) return $addType;
        throw new BasicException(93103);
    }
    /**
     * 编辑商品分类
     * @param $param
     * @return bool
     * @throws BasicException
     */
    public function  saveType($param){
        $saveType = app('model_mall_categories')->where('id',$param['id'])->update($param);
        if ($saveType!==false) return true;
        throw new BasicException(93104);
    }

    /**
     * 删除商品分类
     * @param $param
     * @return bool
     * @throws BasicException
     */
    public function  delType($param){
        $delType = app('model_mall_categories')->whereIn('id',$param)->delete();
        if ($delType) return $delType;
        throw new BasicException(93105);
    }

    //新增或编辑分类（新商城）
    public function addOrEdit($param)
    {
        $id = $param['id'] ?? 0;
        $parentId = $param['parent_id'];
        $cateName = $param['cate_name'];
        $icon = $param['icon'] ?? '';
        $sort = $param['sort'];
        $isShow = $param['is_show'];
        $isJoinSuit = $param['is_join_suit'] ?? 0;
        $isJoinDiscount = $param['is_join_discount'] ?? 0;
        $isJoinActivity = $param['is_join_activity'] ?? 0;
        $isJoinNobility = $param['is_join_nobility'] ?? 0;
        $isJoinRarity = $param['is_join_rarity'] ?? 0;

        //折扣商品分类名称必须包含数字，根据分类名称得到折扣率
        if ($parentId == MallEnum::PRODUCT_CATE_ID_DISCOUNT) { //折扣分类自动维护折扣率，根据名称分析得出
            $value = $this->discountNameToRate($cateName);
        } else if ($parentId == MallEnum::PRODUCT_CATE_ID_RARITY) { //珍藏分类自动维护稀有等级，从1开始递增
            $maxValue = app('model_mall_categories')
                ->where('parent_id', $parentId)->orderBy('value', 'desc')
                ->value('value');
            if ($maxValue) $value = $maxValue + 1;
            else $value = 1;
        } else {
            $value = '';
        }

        $cate = app('model_mall_categories')
            ->where('title', $cateName)
            ->where(function ($query) use ($id) {
                if ($id >0) {
                    $query->where('id', '<>', $id);
                }
            })->first();
        if ($cate) throw new BasicException(0, '分类名称已经存在');

        $data = [
            'parent_id' => $parentId,
            'title' => $cateName,
            'value' => $value,
            'icon' => $icon,
            'sort' => $sort,
            'is_show' => $isShow,
            'is_join_suit' => $isJoinSuit,
            'is_join_discount' => $isJoinDiscount,
            'is_join_activity' => $isJoinActivity,
            'is_join_nobility' => $isJoinNobility,
            'is_join_rarity' => $isJoinRarity,
        ];
        if ($id > 0) {
            $action = '编辑';
            $res = app('model_mall_categories')->where('id', $id)->update($data);
        } else {
            $action = '添加';
            $data['add_time'] = time();
            $res = app('model_mall_categories')->insert($data);
        }

        if ($res) {
            return Response::sendData([]);
        } else {
            throw new BasicException(0, $action.'失败');
        }
    }

    //根据折扣名称得到折扣率
    private function discountNameToRate($discountName)
    {
        $discountMap = [
            '一' => 1,
            '二' => 2,
            '三' => 3,
            '四' => 4,
            '五' => 5,
            '六' => 6,
            '七' => 7,
            '八' => 8,
            '九' => 9,
            '1' => 1,
            '2' => 2,
            '3' => 3,
            '4' => 4,
            '5' => 5,
            '6' => 6,
            '7' => 7,
            '8' => 8,
            '9' => 9,
        ];
        $discountKeywords = array_keys($discountMap);

        $validKeywordCount = 0; //折扣名称中包含的有效关键字个数，可以是1-2个
        for ($i = 0; $i < mb_strlen($discountName); $i++) {
            $char = mb_substr($discountName, $i, 1);
            if (in_array($char, $discountKeywords)) {
                $validKeywordCount++;
                if ($validKeywordCount == 1) {
                    $minDiscount = $discountMap[$char] * 10;
                    $maxDiscount = $discountMap[$char] * 10 + 9;
                } else if ($validKeywordCount == 2) {
                    $minDiscount += $discountMap[$char];
                    $maxDiscount = $minDiscount;
                }
            }
        }
        if ($validKeywordCount == 0) {
            throw new BasicException(0, '折扣分类名称必须含有折扣关键字，可以是语文数字一到九或阿拉伯数字1到9');
        }
        if ($minDiscount == $maxDiscount) {
            return $minDiscount;
        } else {
            return $minDiscount . ',' . $maxDiscount;
        }
    }

    //新增或编辑金刚区分类（v3.6）
    public function addOrEditIndexCate($param)
    {
        $id = $param['id'] ?? 0;
        $cateName = $param['cate_name'];
        $icon = $param['icon'];
        $isShow = $param['is_show'];
        $sort = $param['sort'];

        $cate = app('model_mall_categories')
            ->where('title', $cateName)
            ->where(function ($query) use ($id) {
                if ($id > 0) {
                    $query->where('id', '<>', $id);
                }
            })
            ->first();
        if ($cate) throw new BasicException(0, '分类名称已经存在');

        $data = [
            'new_parent_id' => 0,
            'title' => $cateName,
            'icon' => $icon,
            'is_show' => $isShow,
            'sort' => $sort,
            'add_time' => time(),
        ];

        if ($id > 0) {
            $cate = app('model_mall_categories')->select('id')->where('id', $id)->first();
            if (empty($cate)) throw new BasicException(0, '分类id错误');

            return app('model_mall_categories')->where('id', $id)->update($data);
        } else {
            return app('model_mall_categories')->insertGetId($data);
        }
    }
}


